package com.sun.dream.fish.service.impl;

import com.sun.dream.fish.service.IFileService;
import io.micrometer.common.util.StringUtils;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;

@Service
@Slf4j
public class FileServiceImpl implements IFileService {
    private static final String STORE_PATH = "storeFile" + File.separator;

    @Override
    public boolean storeExcelFile(MultipartFile file, String newName) {
        File newFile = new File(STORE_PATH + handlerFileName(file.getOriginalFilename(), newName));
        try (FileOutputStream fileOutputStream = new FileOutputStream(newFile)) {
            fileOutputStream.write(file.getBytes());
        } catch (Exception e) {
            log.error("【FileServiceImpl】异常 ： ", e);
            return false;
        }
        return true;
    }

    @Override
    public FileSystemResource downloadExcelFile(String fileName) {
        if (StringUtils.isEmpty(fileName)) {
            return new FileSystemResource(new File(STORE_PATH + "lll.sql"));
        }
        File[] files = new File(STORE_PATH).listFiles((dir, name) -> fileName.equalsIgnoreCase(name.substring(0, name.indexOf("."))));
        if (files == null || files.length == 0) {
            return null;
        } else {
            return new FileSystemResource(files[0]);
        }
    }

    private String handlerFileName(String originalFilename, String name) {
        assert !StringUtils.isEmpty(originalFilename);
        assert !StringUtils.isEmpty(name);
        return name + originalFilename.substring(originalFilename.indexOf("."));
    }
}
